package com.wxdc.nmgyt.nmgytwydc.fragment;

import android.Manifest;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.Overlay;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.PolylineOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.TextOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.esri.core.geometry.GeometryEngine;
import com.esri.core.geometry.Point;
import com.esri.core.geometry.Polygon;
import com.esri.core.geometry.SpatialReference;
import com.syd.oden.circleprogressdialog.core.CircleProgressDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wxdc.nmgyt.nmgytwydc.IMapFunInterface.IMapFunInterface;
import com.wxdc.nmgyt.nmgytwydc.R;
import com.wxdc.nmgyt.nmgytwydc.app.MyApp;
import com.wxdc.nmgyt.nmgytwydc.common.MyCircleProgressDialog;
import com.wxdc.nmgyt.nmgytwydc.utils.SaveGpsDataUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import it.beppi.tristatetogglebutton_library.TriStateToggleButton;

import static android.content.Context.SENSOR_SERVICE;

/**
 * Created by Administrator on 2018/4/2.
 */

public class NavigationMapFragment extends Fragment implements SensorEventListener {
    private final String TAG = this.getClass().getSimpleName();
    @BindView(R.id.map_tools_tstb_btn)
    TriStateToggleButton mMapToolsTstbBtn;
    @BindView(R.id.map_tools_tstb_txthint)
    TextView mMapToolsTstbTxthint;
    Unbinder unbinder;
    @BindView(R.id.map_tools_togBtn_LinearLayout)
    LinearLayout mMapToolsTogBtnLinearLayout;
    @BindView(R.id.map_tools_imageBtn_linnearLayout)
    LinearLayout mMapToolsImageBtnLinnearLayout;
    @BindView(R.id.map_tools_imageBtn_mark)
    ImageButton mMapToolsImageBtnMark;
    @BindView(R.id.map_tools_imageBtn_distance)
    ImageButton mMapToolsImageBtnDistance;
    @BindView(R.id.map_tools_imageBtn_area)
    ImageButton mMapToolsImageBtnArea;
    @BindView(R.id.map_tools_imageBtn_txtmark)
    TextView mMapToolsImageBtnTxtmark;
    @BindView(R.id.map_tools_imageBtn_txtdistance)
    TextView mMapToolsImageBtnTxtdistance;
    @BindView(R.id.map_tools_imageBtn_txtarea)
    TextView mMapToolsImageBtnTxtarea;
    @BindView(R.id.baidu_imageBtn_getGps)
    ImageButton mBaiduImageBtnGetGps;
    @BindView(R.id.baidu_imageBtn_saveGpsData)
    ImageButton mBaiduImageBtnSaveGpsData;
    @BindView(R.id.map_gps_value_relativeLayout)
    RelativeLayout mMapGpsValueRelativeLayout;
    @BindView(R.id.toolbar_title)
    TextView mToolbarTitle;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    private MyApp mMyApp;
    private MapView mMapView = null;
    private BaiduMap mBaiduMap;
    private BitmapDescriptor mCurrentMarker;
    private Location location;
    private final int GETLOCATION_SUCCESS = 000;
    private SensorManager mSensorManager;
    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private float mCurrentAccracy;
    private MyLocationData locData;
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private CircleProgressDialog mCircleProgressDialog;
    private int mapToolsFlag = 0;//默认0:不操作；1：标记；2:测距离；3：测面积
    private int measureWay = 0;// 1:触摸获得点信息测量；2：GPS获得点测量
    private List<LatLng> mLatLngs;
    private RxPermissions rxPermissions;
    private AppCompatActivity mActivity;
    private boolean mIsVisibleToUser;
    private Message message;
    private Timer timer;
    private TimerTask mTimerTask;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            switch (message.what) {
                case GETLOCATION_SUCCESS:
                    initLocPosition(location);
                    if (mCircleProgressDialog != null && mCircleProgressDialog.isShowing()) {
                        mCircleProgressDialog.dismiss();
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    });

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Log.i(TAG, "onAttach: -----------------------" + getActivity());
        mMyApp = MyApp.getInstance();
        mActivity = (AppCompatActivity) getActivity();
        message = Message.obtain();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rxPermissions = new RxPermissions(mActivity);
        mSensorManager = (SensorManager) mActivity.getSystemService(SENSOR_SERVICE);//获取传感器管理服务
        mCircleProgressDialog = new CircleProgressDialog(mActivity);
        mCircleProgressDialog.setText("确定当前位置信息...");
        //mCircleProgressDialog.setCancelable(false);
        MyCircleProgressDialog.initCircleProgressDialog(mCircleProgressDialog);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_bdmap, container, false);
        unbinder = ButterKnife.bind(this, view);
        if (mIsVisibleToUser) {
            customToolbar();
        }
        ImageButton loc_btn = view.findViewById(R.id.baidu_loc_btn);//获取地图控件引用
        mMapView = (MapView) view.findViewById(R.id.bmapView);
        mBaiduMap = mMapView.getMap();
        //隐藏地图上百度地图logo图标
        mMapView.removeViewAt(1);
        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                setMapUi();
                rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                        .subscribe(granted -> {
                            if (granted) {
                                getLocationInfo();
                            } else {

                            }
                        });

            }
        });
        loc_btn.setOnClickListener(new myLocListener());
        //
        mMapToolsTstbBtn.setOnToggleChanged(new TriStateToggleButton.OnToggleChanged() {
            @Override
            public void onToggle(TriStateToggleButton.ToggleStatus toggleStatus, boolean b, int i) {
                switch (toggleStatus) {
                    case off:
                        mMapToolsImageBtnLinnearLayout.setVisibility(View.GONE);
                        mMapGpsValueRelativeLayout.setVisibility(View.GONE);
                        mMapToolsTstbTxthint.setText("");
                        measureWay = 0;
                        mapToolsFlag = 0;
                        mBaiduMap.clear();
                        mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                        mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                        mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                        break;
                    case mid://屏幕触摸测量
                        mMapToolsImageBtnLinnearLayout.setVisibility(View.VISIBLE);
                        mMapToolsTstbTxthint.setText("touch");
                        measureWay = 1;
                        if (mLatLngs == null) {
                            mLatLngs = new ArrayList<>();
                        }
                        mLatLngs.clear();
                        mBaiduMap.clear();
                        break;
                    case on://获得GPS测量
                        mMapToolsTstbTxthint.setText("gps");
                        mMapGpsValueRelativeLayout.setVisibility(View.VISIBLE);
                        measureWay = 2;
                        if (mLatLngs == null) {
                            mLatLngs = new ArrayList<>();
                        }
                        mLatLngs.clear();
                        mBaiduMap.clear();
                        break;
                }
            }
        });
        //--------------------百度地图触摸事件
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                Log.i(TAG, "onMapClick: ------------" + latLng.latitude);
                if (measureWay == 1) {
                    switch (mapToolsFlag) {
                        case 1://标记点
                            drawDot(latLng, true);
                            break;
                        case 2://测距离
                            mLatLngs.add(latLng);
                            if (mLatLngs.size() < 2) {
                                drawDot(latLng, true);
                            } else {
                                drawDot(latLng, true);
                                drawPolyLine(mLatLngs, true);
                            }
                            break;
                        case 3://测面积
                            mLatLngs.add(latLng);
                            if (mLatLngs.size() < 3) {
                                drawDot(latLng, true);
                                mMyApp.showToastShortMessage(mActivity, "三点确定一个面");
                            } else {
                                drawDot(latLng, true);
                                drawPolyGon(mLatLngs, true);
                            }
                            break;
                    }
                }
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });
        return view;
    }

    /*
        * */
    private void customToolbar() {
        //fragment中使用toolbar
        mActivity.setSupportActionBar(mToolbar);
        mActivity.getSupportActionBar().setTitle("");
        mToolbarTitle.setText(R.string.main_toolbar_title_baidu);
        setHasOptionsMenu(true);

    }
    /*
     Fragment 可见加载toolBar
     * */

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        mIsVisibleToUser = isVisibleToUser;
        if (isVisibleToUser && mActivity != null) {
            customToolbar();
        }
    }

    /*
        * 获取位置信息*/
    private boolean isFirstCurrtLocation;//是否第一次定位当前位置

    private void getLocationInfo() {
        isFirstCurrtLocation = true;
        if (location == null) {
            mCircleProgressDialog.showDialog();
        }
        startTimer();
    }

    private void startTimer() {//启动timer
        if (timer == null) {
            timer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    location = mMyApp.getMyBinder().getLocation();
                    if (location != null && isFirstCurrtLocation) {
                        message.what = GETLOCATION_SUCCESS;
                        mHandler.sendMessage(message);
                        isFirstCurrtLocation = false;
                    }
                }
            };
        }
        if (timer != null && mTimerTask != null) {
            timer.schedule(mTimerTask, 0, 2 * 1000);
        }
    }
    private void stopTimer(){//停止timer
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
    /*定位初始化*/
    private void initLocPosition(Location location) {
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 构造定位数据  accuracy:定位精度;direction:GPS定位时方向角度
        LatLng mLatLng = mMyApp.latLngConVert(new LatLng(location.getLatitude(), location.getLongitude()));
        if (mLatLng == null) {
            return;
        }
        Log.i(TAG, "initLocPosition: -------" + mLatLng.latitude + "---" + location.getLongitude() + "--" + location.getLatitude());
        mCurrentAccracy = 100;//当前定位精度
        mCurrentLat = mLatLng.latitude;
        mCurrentLon = mLatLng.longitude;
        locData = new MyLocationData.Builder()
                .accuracy(mCurrentAccracy)
                // 此处设置开发者获取到的方向信息，顺时针0-360
                .direction(mCurrentDirection).latitude(mCurrentLat)
                .longitude(mCurrentLon).build();
        // 设置定位数据
        mBaiduMap.setMyLocationData(locData);
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        mCurrentMarker = BitmapDescriptorFactory
                .fromResource(R.drawable.ic_arrow);
        MyLocationConfiguration config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.NORMAL, true, null);
        mBaiduMap.setMyLocationConfiguration(config);
        mapStatus(16.0f);
    }

    /*
    * 接口SensorEventListener的实现方法
    * */
    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        double x = sensorEvent.values[SensorManager.DATA_X];
        if (Math.abs(x - lastX) > 1.0) {
            mCurrentDirection = (int) x;
            locData = new MyLocationData.Builder()
                    .accuracy(mCurrentAccracy)
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(mCurrentDirection).latitude(mCurrentLat)
                    .longitude(mCurrentLon).build();
            mBaiduMap.setMyLocationData(locData);
        }
        lastX = x;
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    /*定位 Btn click*/
    class myLocListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            mMyApp.checkLocaltionPermissions(mActivity);
            location = ((IMapFunInterface) mActivity).getLocation();
            if (location == null) {
                mMyApp.showToastShortMessage(mActivity, "无法获取定位信息，请检查GPS是否打开");
                return;
            }
            if (!mBaiduMap.isMyLocationEnabled()) {
                initLocPosition(location);
            } else {
                mapStatus(18.0f);
            }

        }
    }

    /*设置地图UI控制器*/
    private void setMapUi() {
        if (mBaiduMap != null) {
            UiSettings uiSettings = mBaiduMap.getUiSettings();
            uiSettings.setAllGesturesEnabled(true);//设置是否允许所有手势操作
            uiSettings.setCompassEnabled(true);//设置是否允许指南针(默认允许true，当地图发生旋转和视角变化时，默认出现在左上角的指南针)
        }
    }

    /*以动画方式更新地图状态*/
    private void mapStatus(float level) {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(mMyApp.latLngConVert(new LatLng(location.getLatitude(), location.getLongitude()))).zoom(level);
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
    }

    /*添加菜单*/
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        Log.i(TAG, "onCreateOptionsMenu: ------------baiduFragmentMap------------" + menu);
        menu.clear();
        inflater.inflate(R.menu.baidu_fragment_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    /*
        * 菜单选中事件
        * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int selectID = item.getItemId();
        switch (selectID) {
            case R.id.bf_menu_item_onlineMap:
                break;
            case R.id.bf_menu_item_localMap:
                if (mActivity instanceof IMapFunInterface) {
                    ((IMapFunInterface) mActivity).switchMap("localArcgisMap");
                }
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    /*
    * 地图操作工具菜单|GPS打点
    * */
    @OnClick({R.id.map_tools_imageBtn_mark, R.id.map_tools_imageBtn_distance, R.id.map_tools_imageBtn_area, R.id.baidu_imageBtn_getGps, R.id.baidu_imageBtn_saveGpsData})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.map_tools_imageBtn_mark:
                mapToolsFlag = 1;
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                mBaiduMap.clear();
                mLatLngs.clear();
                break;
            case R.id.map_tools_imageBtn_distance:
                mapToolsFlag = 2;
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                mBaiduMap.clear();
                mLatLngs.clear();
                break;
            case R.id.map_tools_imageBtn_area:
                mapToolsFlag = 3;
                mMapToolsImageBtnTxtarea.setTextColor(getResources().getColor(R.color.red));
                mMapToolsImageBtnTxtmark.setTextColor(getResources().getColor(R.color.white));
                mMapToolsImageBtnTxtdistance.setTextColor(getResources().getColor(R.color.white));
                mBaiduMap.clear();
                mLatLngs.clear();
                break;
            case R.id.baidu_imageBtn_getGps://获得GPS点(利用GPS点测量)
                rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                        .subscribe(granted -> {
                            if (granted) {
                                utilizeGps();
                            }
                        });
                break;
            case R.id.baidu_imageBtn_saveGpsData://保存GPS获得数据信息
                rxPermissions.request(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                // All requested permissions are granted
                                SaveGpsDataUtil gpsDataUtil = new SaveGpsDataUtil(mActivity);
                                gpsDataUtil.saveGpsDataInfoByBaidu(mLatLngs, mBaiduMap);
                            }
                        });
                break;
        }
    }

    private void utilizeGps() {//利用GPS点测量
        if (location == null) {
            mMyApp.showToastLongMessage(mActivity, "GPS点获得失败");
            return;
        }
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        mLatLngs.add(latLng);
        if (measureWay == 2) {//测量方式
            switch (mapToolsFlag) {
                case 1://标记
                    drawDot(latLng, false);
                    break;
                case 2://测距离
                    if (mLatLngs.size() < 2) {
                        drawDot(latLng, false);
                    } else {
                        drawDot(latLng, false);
                        drawPolyLine(mLatLngs, false);
                    }
                    break;
                case 3://测面积
                    if (mLatLngs.size() < 3) {
                        drawDot(latLng, false);
                        mMyApp.showToastShortMessage(mActivity, "三点确定一个面");
                    } else {
                        drawDot(latLng, false);
                        drawPolyGon(mLatLngs, false);
                    }
                    break;
            }
        }
    }

    /**
     * 画Dot,Polyline,Polygon
     */
    private Overlay overlay_polygon, overlay_polyline, overlay_text;

    private void drawDot(LatLng latLng, boolean isBD0911) {
        /*DotOptions dotOptions = new DotOptions()
                .center(latLng).color(R.color.blue)
                .visible(true).radius(8);*/
        LatLng mLatLng;
        if (isBD0911) {
            mLatLng = latLng;
        } else {
            mLatLng = mMyApp.latLngConVert(latLng);
        }
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.map_tool_point);
        OverlayOptions markerOptions = new MarkerOptions()
                .position(mLatLng).icon(bitmapDescriptor).visible(true);
        mBaiduMap.addOverlay(markerOptions);
    }

    private void drawPolyLine(List<LatLng> points, boolean isBD0911) {//至少两个点
        if (null != overlay_polyline) {
            overlay_polyline.remove();
        }
        List<LatLng> mLatLngs;
        if (isBD0911) {
            mLatLngs = points;
        } else {
            mLatLngs = new ArrayList<>();
            int len = points.size();
            for (int i = 0; i < len; i++) {
                mLatLngs.add(mMyApp.latLngConVert(points.get(i)));
            }
        }
        OverlayOptions polylineOptions = new PolylineOptions()
                .points(mLatLngs).color(0xAA00FF00).width(8);
        int len = points.size();
        double totalnum = 0;
        for (int i = 1; i < len; i++) {
            double distance = DistanceUtil.getDistance(mLatLngs.get(i), mLatLngs.get(i - 1));//返回两个点之间的距离
            totalnum += distance;
            TextOptions textOptions = new TextOptions().position(mLatLngs.get(i)).zIndex(120).fontSize(48).fontColor(getResources().getColor(R.color.red));
            textOptions.text(String.format("%.2f", distance) + "m | " + String.format("%.2f", totalnum) + "m");
            mBaiduMap.addOverlay(textOptions);
        }

        overlay_polyline = mBaiduMap.addOverlay(polylineOptions);
    }
    //画多边形

    /**
     * 通过Gps坐标点画多边形，注意两点：1.传过来的坐标点是Gps点，在百度地图上显示需要进行坐标转换在显示
     * 2.利用arcgis api 计算多边形面积，直接使用传过来的点进行计算
     *
     * @param latLngs
     */
    private void drawPolyGon(List<LatLng> latLngs, boolean isBD0911) {//至少三个点
        OverlayOptions polygonOption = null;
        if (null != overlay_polygon) {
            overlay_polygon.remove();
            overlay_text.remove();
        }
        List<LatLng> mlLatLngList;
        if (isBD0911) {
            mlLatLngList = latLngs;
        } else {
            mlLatLngList = new ArrayList<>();
            int tempLen = latLngs.size();
            for (int i = 0; i < tempLen; i++) {
                mlLatLngList.add(mMyApp.latLngConVert(latLngs.get(i)));
            }
        }
        polygonOption = new PolygonOptions()
                .points(mlLatLngList)
                .stroke(new Stroke(5, 0xAA00FF00))
                .fillColor(0xAAFFFF00);
        overlay_polygon = mBaiduMap.addOverlay(polygonOption); //在地图上添加多边形Option，用于显示
        Polygon arcgis_Polygon = new Polygon();
        // 利用arcgis sdk 计算polygon面积
        if (mlLatLngList.size() > 1) {
            int len = mlLatLngList.size();
            for (int i = 0; i < len; i++) {
                if (i == 0) {
                    arcgis_Polygon.startPath((Point) GeometryEngine.project(new Point(mlLatLngList.get(i).longitude, mlLatLngList.get(i).latitude), SpatialReference.create(SpatialReference.WKID_WGS84), SpatialReference.create(SpatialReference.WKID_WGS84_WEB_MERCATOR)));
                } else {
                    arcgis_Polygon.lineTo((Point) GeometryEngine.project(new Point(mlLatLngList.get(i).longitude, mlLatLngList.get(i).latitude), SpatialReference.create(SpatialReference.WKID_WGS84), SpatialReference.create(SpatialReference.WKID_WGS84_WEB_MERCATOR)));
                }
            }
            double area = Math.abs(arcgis_Polygon.calculateArea2D());
            TextOptions textOptions = new TextOptions().zIndex(120).fontColor(getResources().getColor(R.color.red)).fontSize(36).
                    position(mlLatLngList.get(mlLatLngList.size() - 1)).text(String.format("%.2f", Math.abs(area)) + "㎡");
            overlay_text = mBaiduMap.addOverlay(textOptions);
        }
    }
    /*生命周期*/

    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_UI);
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.i(TAG, "onStop: -------------onStop");
        //取消注册传感器监听
        mSensorManager.unregisterListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "onDestroy: ------------onDestory");
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mCircleProgressDialog = null;
        mActivity = null;
        stopTimer();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.i(TAG, "onDetach: ---------------onDetach");
    }
    /**/
}
